package com.yicong.ants.wxapi;


import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import com.cchao.simplelib.core.UiHelper;
import com.cchao.simplelib.util.StringHelper;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yicong.ants.Constants;
import com.yicong.ants.R;

public class WXEntryActivity extends Activity implements IWXAPIEventHandler {

    //这两个参数在文档中没有找到，可能是瞎了,,,自己在代码里面找了会才找到，这两个常量代表了微信返回的消息类型，是对登录的处理还是对分享的处理，登录会在后面介绍到
    private static final int RETURN_MSG_TYPE_LOGIN = 1;
    private static final int RETURN_MSG_TYPE_SHARE = 2;

    private static final String TAG = "WXEntryActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.common_empty);

        //如果没回调onResp，八成是这句没有写
        WXAPIFactory.createWXAPI(this, Constants.WeChatId).handleIntent(getIntent(), this);
    }

    //微信发送消息给app，app接受并处理的回调函数
    @Override
    public void onReq(BaseReq baseReq) {

    }

    //app发送消息给微信，微信返回的消息回调函数,根据不同的返回码来判断操作是否成功
    @Override
    public void onResp(BaseResp resp) {

        if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp;
            String extraData = launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
            Log.d(TAG, "onResp   ---   " + extraData);
            String msg = "onResp   ---   errStr：" + resp.errStr + " --- errCode： " + resp.errCode + " --- transaction： "
                    + resp.transaction + " --- openId：" + resp.openId + " --- extMsg：" + launchMiniProResp.extMsg;
            Log.d(TAG, msg);
            if (StringHelper.isNotEmpty(resp.errStr)) {
                Toast.makeText(this, resp.errStr, Toast.LENGTH_LONG).show();
            }
            finish();
        }
        switch (resp.errCode) {
            case BaseResp.ErrCode.ERR_AUTH_DENIED:
            case BaseResp.ErrCode.ERR_USER_CANCEL:
//                UiHelper.showToast("微信分享失败");
                finish();
                break;
            case BaseResp.ErrCode.ERR_OK:
                switch (resp.getType()) {
                    case RETURN_MSG_TYPE_SHARE:
                        UiHelper.showToast("微信分享成功");
                        finish();
                        break;
                }
                break;
        }

    }
}
